package com.party.web.biz.wechat;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.party.api.dto.wechat.requst.CustomRequest;
import com.party.api.dto.wechat.requst.CustomText;
import com.party.api.dto.wechatPlatform.response.WechatAuthorizerInfoResponse;
import com.party.api.service.wechat.IWechatService;
import com.party.api.service.wechatPlatform.IWechatPlatformService;
import com.party.common.constant.Constant;
import com.party.common.constant.WechatConstant;
import com.party.common.redis.StringJedis;
import com.party.common.utils.StringUtils;
import com.party.common.utils.refund.WechatPayUtils;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.model.wechatPlatform.WechatOpenPlatform;
import com.party.core.service.wechat.IWechatMessageService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.core.service.wechatPlatform.IWechatOpenPlatformService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;


/**
 * 微信服务接口
 * Created by wei.li
 *
 * @date 2017/5/19 0019
 * @time 11:31
 */

@Service
public class WechatBizService {

    //微信接口凭证
    public static final String ACCESS_TOKEN = "ACCESS_TOKEN";

    @Autowired
    private StringJedis stringJedis;

    @Autowired
    private IWechatMessageService wechatMessageService;

    @Autowired
    private IWechatPlatformService wechatPlatformService;

    @Autowired
    private IWechatOpenPlatformService wechatOpenPlatformService;

    @Autowired
    private IWechatService wechatService;

    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;

    @Value("#{wechat_platform['wechat.platform.appId']}")
    private String componentAppid;

    protected static Logger logger = LoggerFactory.getLogger(WechatBizService.class);

    /**
     * 微信长连接转短连接
     *
     * @param longUrl     长连接
     * @param accessToken 交互令牌
     * @return 返回连接
     */
    public String longToShort(String longUrl, String accessToken) {
        String url = WechatConstant.LONG_TO_SHORT_URL.replace(ACCESS_TOKEN, accessToken);
        Map<String, Object> requestMap = Maps.newHashMap();
        requestMap.put("access_token", accessToken);
        requestMap.put("action", "long2short");
        requestMap.put("long_url", longUrl);
        String requestData = JSONObject.toJSONString(requestMap);
        logger.info("微信长连接转短链接请求报文{}", requestData);
        String responseData = WechatPayUtils.httpsPost(url, requestData);
        logger.info("微信长连接转短连接响应报文{}", responseData);

        if (StringUtils.isNotEmpty(responseData)) {
            Map<String, String> responseMap = JSONObject.parseObject(responseData, Map.class);
            return responseMap.get("short_url");
        }
        return null;
    }

    /**
     * 长连接转短连接
     * @param longUrl 长连接
     * @param publisher 发布者
     * @return
     */
    public String longToShort2(String longUrl, String publisher) {
        String token = null;
        if (StringUtils.isNotEmpty(publisher)) {
            // 如果发布者绑定了自己的商户，就使用自己的token，否则就使用系统的token
            WechatOpenMember wechatOpenMember = wechatOpenMemberService.findByMemberId(publisher);
            if (null != wechatOpenMember) {
                token = wechatOpenMember.getAuthorizerAccessToken();
            }
            if (StringUtils.isEmpty(token)) {
                wechatOpenMember = wechatOpenMemberService.getSystem();
                token = wechatOpenMember.getAuthorizerAccessToken();
            }
        } else {
            WechatOpenMember wechatOpenMember = wechatOpenMemberService.getSystem();
            token = wechatOpenMember.getAuthorizerAccessToken();
        }
        return longToShort(longUrl, token);
    }


    /**
     * 回复关注
     * @param openId openid
     * @param memberId 会员编号
     * @return 关注回复
     */
    public String replyFocus(String openId, String memberId){
        String url = stringJedis.getValue(Constant.ATTENTION_URL_KEY + openId);
        String partnerName = stringJedis.getValue(Constant.ATTENTION_PARTNER_NAME + openId);
        logger.info("获取缓存的关注连接key{}，value{}", Constant.ATTENTION_URL_KEY + openId, url);
        if (null != url){
            StringBuilder stringBuilder = new StringBuilder("<a href=\"")
                    .append(url).append("\">请点击访问之前的连接</a>");
            if (StringUtils.isNotEmpty(partnerName)) {
                stringBuilder = new StringBuilder("<a href=\"")
                        .append(url)
                        .append("\">请点击访问之前的连接 【" + partnerName + "】</a>");
            }
            return stringBuilder.toString();
        }
        stringJedis.delete(Constant.ATTENTION_URL_KEY + openId);
        stringJedis.delete(Constant.ATTENTION_PARTNER_NAME + openId);
        stringJedis.delete(Constant.ATTENTION_UNIQUE_CODE_KEY + openId);
        return wechatMessageService.replyFocus(memberId);
    }

    /**
     * 回复api文本消息
     * @param authCode 授权码
     * @param fromUserName 接受者
     */
    public void replyApiMessage(String authCode, String fromUserName){

        WechatOpenPlatform wechatOpenPlatform = wechatOpenPlatformService.get();
        WechatAuthorizerInfoResponse authorizationInfo
                = wechatPlatformService.getAuthorizationInfo(componentAppid, wechatOpenPlatform.getComponentAccessToken(), authCode);

        CustomRequest customRequest = new CustomRequest();
        CustomText customText = new CustomText();
        customText.setContent(authCode + "_from_api");
        customRequest.setTouser(fromUserName);
        customRequest.setMsgType("text");
        customRequest.setCustomText(customText);
        wechatService.customSend(customRequest, authorizationInfo.getAuthorization_info().getAuthorizer_access_token());

    }
}
